import cv2
import subprocess
import glob
import os
import shutil
from datetime import timedelta
from common.file_utils import (
    get_uploaded_video_path, output_in_video_dir, output_video_dir as get_output_video_path)




def extract_keyframes(input_video_name: str):
    input_video_path = get_uploaded_video_path(input_video_name)
    in_video_path = output_in_video_dir(input_video_name)
    key_frame_dir = 'keyframes'
    if not os.path.exists(key_frame_dir):
        os.makedirs(key_frame_dir)

    # 提取关键帧
    call_extract_keyframes(input_video_path, key_frame_dir)

    output_video_path = get_output_video_path(input_video_name)
    remove_static_background(key_frame_dir, output_video_path)
    shutil.copy(output_video_path, in_video_path)
    delete_jpg_keyframes(key_frame_dir)

    return output_video_path


def call_extract_keyframes(input_video, output_folder, threshold=0.005):
    # 使用FFmpeg提取关键帧
    subprocess.run(
        f'ffmpeg -i {input_video} -vf "select=gt(scene\,{threshold}),setpts=N/FRAME_RATE/TB" -vsync vfr {output_folder}/%05d.jpg', shell=True)


def remove_static_background(input_folder, output_video, threshold=0.005):

    # 使用OpenCV检测静态背景帧
    img_list = sorted(glob.glob(f'{input_folder}/*.jpg'))
    print(f"图像列表: {img_list}")
    bg_img = cv2.imread(img_list[0])
    bg_gray = cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY)
    height, width = bg_gray.shape

    # 创建视频编写器
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_video, fourcc, 30.0, (width, height))

    for img_path in img_list:
        img = cv2.imread(img_path)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        """
        # 计算图像差异
        diff = cv2.absdiff(gray, bg_gray)
        diff_mean = diff.mean()
        print(diff_mean)

        # 如果差异超过阈值，则将帧写入输出视频中
        if diff_mean > threshold:
            out.write(img)
        """
        out.write(img)
        # 更新背景图像
        bg_gray = gray.copy()

    # 释放资源
    out.release()


def delete_jpg_keyframes(folder_path):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(".jpg"):
                file_path = os.path.join(root, file)
                os.remove(file_path)
